package com.glodon.zhuanli.front.web;

import com.glodon.infrastructure.support.login.web.LoginController;
import com.glodon.zhuanli.ZLConstants;
import com.glodon.zhuanli.front.servcie.ZhuanliLoginUserService;
import com.glodon.zhuanli.system.entity.SysUser;
import com.glodon.zhuanli.system.service.SysRoleService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Controller
public class ZhuanliLoginController extends LoginController {

    @Autowired
    private ZhuanliLoginUserService zhuanliLoginUserService ;

    @Autowired
    private SysRoleService sysRoleService ;

    @Override
    public void loginPageHandler(String type , ModelAndView mv){
        mv.setViewName("/front/"+BASE_PATH) ;
    }

    protected SysUser getAuthenticatedSysUser(){
        Subject subject = SecurityUtils.getSubject() ;
        Object principal = subject.getPrincipal() ;
        return principal==null ? null : (SysUser)principal ;
    }

    @Override
    public ResponseEntity<Map<String, Object>> loginSubmit(HttpServletRequest request){
        Map<String, Object> loginResultMap = Maps.newHashMap() ;
        //登录成功的标识
        loginResultMap.put("success" , isAuthenticated()) ;
        if(isAuthenticated()){
            //登录成功之后的处理
            SysUser loginUser = getAuthenticatedSysUser() ;
            if(loginUser!=null){
                log.info("登录成功，开始对登录用户进行处理。");
            }else{
                throw new IllegalArgumentException("由认证中获取用户对象失败。") ;
            }
            //登陆成功之后返回sessionid
            loginResultMap.put("sid" , request.getSession().getId()) ;
            loginResultMap.put("message" , "登录成功。") ;
            loginResultMap.put("successurl" , getDefaultLoginSuccessURL() ) ;
        }else{
            //默认登陆失败信息
            String message = "登录失败。" ;
            //获取异常类型
            Object exception = request.getAttribute("exception") ;
            if(exception!=null && exceptionMessageMap.containsKey(exception.getClass())){
                message = exceptionMessageMap.get(exception.getClass()) ;
            }
            loginResultMap.put("message" , message) ;
        }

        doAfterLoginComplete(request , loginResultMap) ;

        ResponseEntity<Map<String, Object>> responseEntity =
                new ResponseEntity<Map<String, Object>>(loginResultMap, HttpStatus.OK) ;

        return responseEntity ;
    }

    @Override
    public void doAfterLoginComplete(HttpServletRequest request , Map<String, Object> loginResult){
        boolean loginSuccess = (Boolean) loginResult.get("success") ;
        if( !loginSuccess ){
            return ;
        }

        SysUser sysUser = getAuthenticatedSysUser() ;
        boolean flag = sysRoleService.isAdmin( sysUser.getRoleId() ) ;
        if( flag ){
            log.info("当前登录用户为管理员，不设置所属机构");
        }else{
            //设置用户所属机构的id
            request.getSession().setAttribute(ZLConstants.SESSION_USER_ORGID , sysUser.getOrgId()) ;
            log.info("当前登录用户所属机构为: {}" , sysUser.getOrgId());
            //设置当前用户所属的服务机构或企业的id
            if(StringUtils.isNotBlank( sysUser.getCompanyId() ) &&
                    StringUtils.equalsIgnoreCase( sysUser.getSource() , ZLConstants.RECORD_SOURCE.COMPANY )){
                request.getSession().setAttribute( ZLConstants.SESSION_USER_COMPANYID  , sysUser.getCompanyId() );
            }
        }

        zhuanliLoginUserService.updateSessionUser( request  , sysUser ) ;

        zhuanliLoginUserService.updateSessionMenu( request , sysUser ) ;

    }

}
